using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
using System.Data;

namespace LiveStock.RssObjects
{
    class TypedDataSetLoader:IDataSetLoader
    {

        private DataSet theDataSet;

        public TypedDataSetLoader(DataSet ds)
        {
            theDataSet = ds;
        }

        public void Fill(Stream s)
        {
            DataSet ds = new DataSet();
            ds.ReadXml(s);
            s.Close();

            Fill(ds);
        }

        public void Fill(XmlDocument doc)
        {
            byte[] buf = System.Text.ASCIIEncoding.ASCII.GetBytes(doc.OuterXml);
            MemoryStream ms = new MemoryStream(buf);
        }

        public void Fill(DataSet ds)
        {
            //turn off constraints during load in case data loads in wrong order
            theDataSet.EnforceConstraints = false;

            for (int i = 0; i < ds.Tables.Count; i++)
            {
                foreach (DataRow dsRow in ds.Tables[i].Rows)
                {
                    //get current table name so that the tables map correctly
                    string tablename = ds.Tables[i].TableName;

                    DataRow newRow = theDataSet.Tables[tablename].NewRow();
                    for (int j = 0; j < ds.Tables[tablename].Columns.Count; j++)
                    {
                        //get column name so that columns and column types match
                        string columnName = ds.Tables[tablename].Columns[j].ColumnName;
                        try
                        {
                            newRow[columnName] = dsRow[columnName];
                        }
                        catch
                        {
                            //ignore for now just in case no such column in typed dataset
                        }
                    }
                    theDataSet.Tables[tablename].Rows.Add(newRow);
                }
            }

            //enforce constraints after data is loaded
            theDataSet.EnforceConstraints = true;
            theDataSet.AcceptChanges();
        }

        public void ReadXml(string xmlFile)
        {
            XmlDocument xmlDoc = new XmlDocument();
            try
            {
                xmlDoc.Load(xmlFile);
                Fill(xmlDoc);
            }
            catch
            {
            }
        }

    }
}
